package com.ruoyi.web.controller.miniprogram;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.MiniprogramLoginBody;
import com.ruoyi.framework.web.service.MiniprogramLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 小程序登录控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/miniprogram")
public class MiniprogramLoginController
{
    @Autowired
    private MiniprogramLoginService miniprogramLoginService;

    /**
     * 小程序登录
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody MiniprogramLoginBody loginBody)
    {
        try
        {
            // 参数校验
            if (loginBody.getAppId() == null || loginBody.getCode() == null)
            {
                return AjaxResult.error("参数不能为空");
            }

            // 执行登录
            LoginUser loginUser = miniprogramLoginService.miniprogramLogin(loginBody.getAppId(), loginBody.getCode());
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, loginUser.getToken());
            ajax.put("userId", loginUser.getUserId());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error("登录失败：" + e.getMessage());
        }
    }
}
